﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using Kugar.Core.Configuration;
using Kugar.Core.ExtMethod;
using Kugar.ERPFramework.Core.Interfaces;
using System.ComponentModel.Composition;
using Kugar.Core.BaseStruct;
using Kugar.ERPFramework.Core;
using Kugar.ERPFramework.Core.Entity;


namespace Kugar.ERPFramework.Service
{
    [Export(typeof(ICustomBLLModule))]
    [ExportMetadata("ExportInterface",typeof(ISystemModule))]
    public class SystemModule:CustomModuleBase,ISystemModule
    {
        public SystemModule( IProjectInstance projectInstance) : base("SystemModule", projectInstance)
        {

        }


        public ResultReturn<Core.Entity.LoginUserInfo> GetUserInfoByID(int userID)
        {
            return null;
        }

        public ResultReturn<int> Login(string userName, string pw, System.Net.IPAddress address)
        {
            throw new NotImplementedException();
        }

        public EmptyResultReturn Logout()
        {
            throw new NotImplementedException();
        }

        public ResultReturn<string[]> GetUserNameList()
        {
            throw new NotImplementedException();
        }

        public ResultReturn<LoginUserInfo[]> GetOnlineUser()
        {
            throw new NotImplementedException();
        }

        public EmptyResultReturn SetUserOffline(int userID)
        {
            throw new NotImplementedException();
        }

        public EmptyResultReturn SetAllUserOffline()
        {
            throw new NotImplementedException();
        }

        public ResultReturn<Kugar.Core.Security.RMS_PermissionValueCollection> GetCurrentPermission()
        {
            throw new NotImplementedException();
        }

        public ResultReturn<int> SendMessageToUsers(int userID, string message, int[] revUserIDList)
        {
            throw new NotImplementedException();
        }

        public ResultReturn<int> SendMessageToAllUser(string message)
        {
            throw new NotImplementedException();
        }

        public ResultReturn<ICustomConfigSection> GetConfigBySectionName(string sectionName)
        {
            var config=CustomConfigManager.Default[sectionName];

            if (config!=null)
            {
                return new ResultReturn<ICustomConfigSection>(true,config); 
            }
            else
            {
                return new ResultReturn<ICustomConfigSection>(false);
            }
            
        }

        public ResultReturn<string> GetSerialNumber(string moduleID)
        {
            var conn = base.ProjectInstance.CurrentConnection;

            try
            {
                var sn = conn.ExecuteScalar<int>(string.Format("[dbo].[p_sys_GetModuleSerialNumber] '{0}'", moduleID));

                return new ResultReturn<string>(true, sn.ToString());
            }
            catch (Exception ex)
            {
                return new ResultReturn<string>(false,error:ex);
            }
        }

        public EmptyResultReturn UpdateConfig(string sectionName, KeyValuePair<int, string>[] configs)
        {
            throw new NotImplementedException();
        }
    }


    public class UserManager:CustomModuleBase
    {
        private MemoryCache _loginUserCache = new MemoryCache("LoginUserCache");
        

        public UserManager( IProjectInstance projectInstance) : base("UserManager", projectInstance)
        {

        }

        public LoginUserInfo Login(string userName, string password)
        {
            if (CheckUser(userName,password))
            {
                var user = getLoginUserByName(userName);

                user.IsOnline = true;
                
                return user;
            }
            else
            {
                //throw new ArgumentOutOfRangeException("password","密码错误");
                return null;
            }

        }

        public void Logout(string userName)
        {
            //_loginUserCache.Remove(userName);
            var user = getLoginUserByName(userName);

            user.IsOnline = false;
        }

        public bool CheckUser(string userName, string password)
        {
            var user = getLoginUserByName(userName);

            if (user == null)
            {
                return false;
                //throw new ArgumentOutOfRangeException("userName", "不存在指定名称的用户");
            }

            var pw = password.MD5_32().MD5_32();

            return user.Password.CompareTo(pw,true);
        }



        private LoginUserInfo getLoginUserByName(string userName)
        {
            var loginUser =(LoginUserInfo) _loginUserCache.Get(userName);

            if (loginUser!=null)
            {
                return loginUser;
            }


            var context = new Database.EFFrameworkEntityModelContainer(base.ProjectInstance.CurrentConnection.Connection);

            var user = context.sys_User.FirstOrDefault(x => x.UserName == userName);

            if (user != null)
            {
                loginUser = ConvertToView(user);

                _loginUserCache.Set(user.UserName, loginUser, new CacheItemPolicy() { SlidingExpiration = new TimeSpan(0, 20, 0) });

                return loginUser;
            }
            else
            {
                return null;
            }

            
        }

        private LoginUserInfo ConvertToView(Database.sys_User user)
        {
            var loginUser = new LoginUserInfo();

            loginUser.UserID = user.UserID;
            loginUser.UserName = user.UserName;
            loginUser.Password = user.Password;
            loginUser.UserKey = user.UserKey;

            return loginUser;
        }
    }
}
